package org.example.netty.test.nio.netty.chat.handler;

import cn.hutool.crypto.digest.MD5;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.RegisterMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.bean.User;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.common.UserStatus;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.FileUtil;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

/**
 * @author zp
 * @version 1.0
 * @description: 处理RegisterMessage消息
 * @date 2023/4/6 18:52
 */
@Slf4j
public class RegisterMessageHandler extends SimpleChannelInboundHandler<RegisterMessage> {

    @Override
    public void channelRead0(ChannelHandlerContext ctx, RegisterMessage msg) throws Exception {
        log.debug("注册的消息：{}",msg);
        GlobalContent globalContent = GlobalContent.getInstance();
        // 校验注册的姓名是否重复
        if (globalContent.userNameExist(msg.getUserName())) {
            SystemMessage.sendFailMessage(SystemMessageType.REGISTER_USER_NAME_FAIL,ctx);
            return;
        }

        UserSession userSession = new UserSession();
        User user = new User();
        String userName = msg.getUserName();
        String password = msg.getPassword();
        String userId = MD5.create().digestHex16(userName + password, CharsetUtil.UTF_8);
        user.setUserId(userId);
        user.setUserName(msg.getUserName());
        user.setStatus(UserStatus.REGISTER_STATUS);
        userSession.setUser(user);

        globalContent.bind(userId,userSession, ctx.channel());
        FileUtil.writeUserList(userName,password);
        // 脱敏密码
        String replacePassword = NettyChannelUtil.replaceWithAsterisks(msg.getPassword());
        msg.setPassword(replacePassword);
        SystemMessage.sendSuccessMessage(SystemMessageType.REGISTER_SUCCESS,ctx);
        ctx.channel().writeAndFlush(msg);
    }
}
